/**
 * @file alert
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {render} from 'react-dom';
import {
  Component,
  PropTypes
} from 'react';

import {
  Modal,
  Button
} from 'react-bootstrap';
import {getDialogContainer} from '../../util/helper';
import Html from '../html';

export class Alert extends Component {
  static propTypes = {
    className: PropTypes.string
  };

  static instance = null;

  static getInstance() {
    if (!Alert.instance) {
      const container = getDialogContainer();
      const div = document.createElement('div');
      container.appendChild(div);
      render(<Alert/>, div);
    }

    return Alert.instance;
  }

  constructor(props) {
    super(props);

    this._resolve =/* this._reject = */null;

    this.state = {
      show: false,
      title: '温馨提示',
      content: ''
    };

    this.close = this.close.bind(this);
    this.handleConfirm = this.handleConfirm.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.modalRef = this.modalRef.bind(this);
  }

  componentWillMount() {
    Alert.instance = this;
  }

  componentWillUnmount() {
    Alert.instance = null;
  }

  handleConfirm() {
    this.close(true);
  }

  handleCancel() {
    this.close(false);
  }

  close(confirmed) {
    const isConfirm = this.state.confirm;

    this.setState({
      show: false
    }, isConfirm ? () => confirmed ? this._resolve() : null/*this._reject()*/ : null);
  }

  alert(content) {
    this.setState({
      content,
      show: true,
      confirm: false
    });
  }

  confirm(content) {
    this.setState({
      content,
      show: true,
      confirm: true
    });

    return new Promise((resolve, reject) => {
      this._resolve = resolve;
      // this._reject = reject;
    });
  }

  modalRef(ref) {
    this._modal = ref;
  }

  render() {
    return (
      <Modal
        show={this.state.show}
        onHide={this.handleCancel}
        container={getDialogContainer()}
        ref={this.modalRef}
      >
        <Modal.Header closeButton>
          <Modal.Title>{this.state.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Html html={this.state.content} />
        </Modal.Body>
        <Modal.Footer>
          {this.state.confirm ? (
            <Button onClick={this.handleCancel}>取消</Button>
          ) : null}
          <Button bsStyle={this.state.confirm ? 'danger' : 'primary'} onClick={this.handleConfirm}>{this.state.confirm ? '确认' : '知道了'}</Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

export const alert = content => Alert.getInstance().alert(content);
export const confirm = content => Alert.getInstance().confirm(content);
